package services.restaurant.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.entities.Restaurant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import services.restaurant.RestaurantService;
import beans.RestaurantVO;
import daos.restaurant.RestaurantAppDAO;

@Service("restaurantService")
public class RestaurantServiceImpl implements RestaurantService {

    @Autowired
    private RestaurantAppDAO restaurantAppDAO;

    public void insert(RestaurantVO restaurantVO) throws SQLException {
        Restaurant restaurant = populate(restaurantVO);

        this.getRestaurantAppDAO().insert(restaurant);
    }

    public void delete(RestaurantVO restaurantVO) throws SQLException {
        Restaurant restaurant = populate(restaurantVO);

        this.getRestaurantAppDAO().delete(restaurant);
    }

    public void update(RestaurantVO restaurantVO) throws SQLException {
        Restaurant restaurant = populate(restaurantVO);

        this.getRestaurantAppDAO().update(restaurant);
    }

    public List<RestaurantVO> selectAll() throws SQLException {

        return this.populate(getRestaurantAppDAO().selectAll());
    }

    public List<RestaurantVO> selectByName(RestaurantVO restaurantVO)
            throws SQLException {
        Restaurant restaurant = this.populate(restaurantVO);
        return populate(restaurantAppDAO.selectByName(restaurant));
    }

    public boolean exist(RestaurantVO restaurantVO) throws SQLException {
        Restaurant restaurant = populate(restaurantVO);

        return this.getRestaurantAppDAO().exist(restaurant);
    }

    private Restaurant populate(RestaurantVO restaurantVO) {
        Restaurant restaurant = new Restaurant();

        restaurant.setName(restaurantVO.getName());
        restaurant.setCity(restaurantVO.getCity());

        return restaurant;
    }

    private RestaurantVO populate(Restaurant restaurant) {
        RestaurantVO restaurantVO = new RestaurantVO();

        restaurantVO.setName(restaurant.getName());
        restaurantVO.setCity(restaurant.getCity());

        return restaurantVO;
    }

    private List<RestaurantVO> populate(List<Restaurant> restaurants) {
        List<RestaurantVO> restaurantsVO = new ArrayList<RestaurantVO>();

        for (Restaurant restaurant : restaurants) {
            restaurantsVO.add(populate(restaurant));
        }
        return restaurantsVO;
    }

    public RestaurantAppDAO getRestaurantAppDAO() {
        return restaurantAppDAO;
    }

    public void setRestaurantAppDAO(RestaurantAppDAO restaurantAppDAO) {
        this.restaurantAppDAO = restaurantAppDAO;
    }
}
